package com.example.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
public class UploadController {

    @Value("${oss.bucketName}")
    private String bucketName;

    @Value("${oss.endpoint}")
    private String endpoint;

    @Value("${oss.accessKey}")
    private String accessKey;

    @Value("${oss.secretKey}")
    private String secretKey;

    @Value("${oss.bucketEndpoint}")
    private String bucketEndpoint;

    @PostMapping("/upload")
    public String upload(MultipartFile file){
        //创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKey,secretKey);

        if (ossClient.doesBucketExist(bucketName)) {
            System.out.println("你已创建Bucket :" + bucketName);
        } else {
            System.out.println("bucket不存在，创建Bucket: " + bucketName);
            ossClient.createBucket(bucketName);
        }

        //设计一个存储对象
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String filename = file.getOriginalFilename();
        System.out.println("文件名称：" + filename);
        String objectName = sdf.format(new Date()) + "/" + filename;

        //存储对象
        try {
            ossClient.putObject(bucketName,objectName,file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        String httpURL = bucketEndpoint +"/" + objectName;

        return  httpURL;
    }
}
